#include <util.h>


#include <tiros/tiros.h>


/* Tiros debugging from tr_debug.h which is in the tiros src directory
 * */
#include "tr_int.h"
#include "tr_debug.h"  


#define STKSIZE             (TIROS_MIN_CTXT_SZ + 64)
#define NUM_TASKS	     4


/* Stacks for each of our tasks */
osword_t task_stack[NUM_TASKS][STKSIZE];


void idle_task(void *dummy)
{
	while(1) {
		delayms(1000);
	}
}

unsigned char ddata[TIROS_DEBUG_DATA_SZ];



void debug_task(void *dummy)
{
	trtime_t sleep_time;
	int tmp;
	unsigned char *ch;
	secs_to_trtime(5, &sleep_time);
	while(1) {
		(void)os_wake_at(&sleep_time, O_RELATIVE_TIME);
		
		tmp =  osint_snapshot(ddata, TIROS_DEBUG_DATA_SZ );
		for (ch = ddata; tmp; tmp--)
			putchar(*ch++);
		
	}

}


eflag_t notification;
#define TASK2_WAKE_FLAG  0x01

void t0(void *dummy)
{
	trtime_t sleep_time;
	
	secs_to_trtime(3, &sleep_time);
	while(1) {
		delayms(1000);
		eflag_set(&notification, TASK2_WAKE_FLAG ,
			  O_EFLAG_TRIGGER);
		os_wake_at(&sleep_time, O_RELATIVE_TIME);
	}
	
}


void t2(void *dummy)
{
	while(1) {
		eflag_wait(&notification, TASK2_WAKE_FLAG, 0, 0);
		delayms(1000);		
	}
	       
}


void platform_init(void);
int main(void) 
{
	tid_t tasks[NUM_TASKS];
	platform_init();

	/* -------------------------------------------------- */
	os_init();
	
	/* Initialize the event flag */
	eflag_init(&notification, 0);

	/* Task priorities are as follows:
	 * T0: 0
	 * debug_task: 1
	 * T2: 2
	 * idle_task: 3
	 */


	tasks[0] = os_task_create(t0, (osptr_t)0,
				  task_stack[0], STKSIZE, 0); 

	tasks[1] = os_task_create(debug_task, (osptr_t)0,
				  task_stack[1], STKSIZE, 1); 

	tasks[2] = os_task_create(t2, (osptr_t)0,
				  task_stack[2], STKSIZE, 2); 

	tasks[3] = os_task_create(idle_task, (osptr_t)0,
				  task_stack[3], STKSIZE, 3); 

	if (tasks[0] == ILLEGAL_ELEM ||
	    tasks[1] == ILLEGAL_ELEM ||
	    tasks[2] == ILLEGAL_ELEM ||
	    tasks[3] == ILLEGAL_ELEM ) {
		putstring("task creation error\n");
	}


	os_start();
	//putstring("Started OS: Shouldn't reach here\n");
	while (1);
}

